import { defineStore } from 'pinia'
import { getCityRate } from '@/api/loan'

interface LoanState {
  loanType: 'commercial' | 'fund' | 'combination'
  amount: number
  years: number
  rate: number
  paymentMethod: 'equal' | 'decreasing'
  cityCode: string
  cityName: string
  commercialRate: number
  fundRate: number
}

export const useLoanStore = defineStore('loan', {
  state: (): LoanState => ({
    loanType: 'commercial',
    amount: 0,
    years: 30,
    rate: 4.85,
    paymentMethod: 'equal',
    cityCode: '110000',
    cityName: '北京市',
    commercialRate: 4.85,
    fundRate: 3.1
  }),
  
  actions: {
    updateLoanInfo(payload: Partial<LoanState>) {
      Object.assign(this, payload)
    },
    async updateCityInfo(cityCode: string, cityName: string) {
      try {
        const rateInfo = await getCityRate(cityCode)
        this.cityCode = cityCode
        this.cityName = cityName
        this.commercialRate = rateInfo.commercialRate
        this.fundRate = rateInfo.fundRate
        this.rate = this.loanType === 'commercial' ? rateInfo.commercialRate : rateInfo.fundRate
      } catch (error) {
        console.error('获取城市利率失败:', error)
      }
    }
  }
}) 